import { Component, Input, OnInit, ChangeDetectorRef } from '@angular/core';
import { ModalController, LoadingController, ActionSheetController } from '@ionic/angular';
import { CommonService } from 'src/app/core/common/common.service';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';

@Component({
  selector: 'demo-modal-page',
  templateUrl: './demo-modal-page.html'
})
export class DemoModalPage implements OnInit {

  constructor(
    public modalController: ModalController,
    private commonService: CommonService,
    private transfer: FileTransfer,
    private camera: Camera,
    private http: HttpClient,
    public actionSheetController: ActionSheetController,
    public ref: ChangeDetectorRef
  ) { }

  data = {
    id: 0,
    companyName: '',
    companyContactPeople: '',
    companyPhoneNumber: '',
    companyAddress: '',
    companyBusinessLicenseImage: '',
    companyDeliverySocialCreditCode: '',
    naturalDeliveryName: '',
    naturalIdNumber: '',
    naturalPhoneNumber: '',
    naturalPaperworkImage: '',
    property: 1,
    type: 1,
    address: '',
    provinceId: '',
    cityId: '',
    districtId: '',
    shortName: '',
  };

  // 获取传递过来的值
  @Input() id: number;
  @Input() isViewMode: boolean;

  provinceData = [];
  cityData = [];
  districtData = [];
  provinceText = '';
  cityText = '';
  districtText = '';
  imgCompanylist = [];
  imgNatruallist = [];
  disabledSave = false;

  ngOnInit(): void {
    this.get(this.id);
    this.getProvinceList();
    this.imgCompanylist.push({ title: '营业执照图片', imgsrc: 'assets/imgs/upimg.jpg' });
  }

  /**
   * 获取对象
   */
  get(id: number) {
    if (id === 0) return;
    // 获取token
    this.commonService.getToken().then((token) => {
      const headerOptions = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8')
        .set('Authorization', 'Bearer ' + token);
      const condition = `?id=${id}`;
      this.http.get('/api/地址' + condition, { headers: headerOptions })
        .subscribe((res: any) => {
          if (res.code === 1) {
            this.data = res.data;
            if (res.data.naturalPaperworkImage !== '') {
              this.imgNatruallist[0].imgsrc = this.data.naturalPaperworkImage;
            }
            this.getProvinceList();
          }
        });
    })
  }

  /**
   * 新增
   */
  async add() {
    const body = `
    {"companyName":"${this.data.companyName}",
    "companyPhoneNumber":"${this.data.companyPhoneNumber}",
    "companyContactPeople":"${this.data.companyContactPeople}",
    "companyAddress":"${this.data.companyAddress}",
    "companyDeliverySocialCreditCode":"${this.data.companyDeliverySocialCreditCode}",
    "naturalDeliveryName":"${this.data.naturalDeliveryName}",
    "naturalIdNumber":"${this.data.naturalIdNumber}",
    "naturalPhoneNumber":"${this.data.naturalPhoneNumber}",
    "type":"${this.data.type}",
    "property":"${this.data.property}",
    "address":"${this.data.address}",
    "shortName":"${this.data.shortName}",
    "provinceId":"${this.data.provinceId}",
    "cityId":"${this.data.cityId}",
    "companyBusinessLicenseImage":"${this.data.companyBusinessLicenseImage}",
    "naturalPaperworkImage":"${this.data.naturalPaperworkImage}",
    "districtId":"${this.data.districtId}"}`;
    const headerOptions = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8')
      .set('Authorization', 'Bearer ' + await this.commonService.getToken());
    this.http.post('/api/地址', body, { headers: headerOptions })
      .subscribe((res: any) => {
        if (res.code === 1) {
          this.commonService.presentToast(res.message);
          this.dismiss();
        } else {
          this.commonService.presentToast(res.message);
        }
      });
  }

  /**
   * 编辑
   */
  edit() {
    const body = `
    {"companyName":"${this.data.companyName}",
    "companyPhoneNumber":"${this.data.companyPhoneNumber}",
    "companyContactPeople":"${this.data.companyContactPeople}",
    "companyAddress":"${this.data.companyAddress}",
    "companyDeliverySocialCreditCode":"${this.data.companyDeliverySocialCreditCode}",
    "naturalDeliveryName":"${this.data.naturalDeliveryName}",
    "naturalIdNumber":"${this.data.naturalIdNumber}",
    "naturalPhoneNumber":"${this.data.naturalPhoneNumber}",
    "companyBusinessLicenseImage":"${this.data.companyBusinessLicenseImage}",
    "naturalPaperworkImage":"${this.data.naturalPaperworkImage}",
    "type":"${this.data.type}",
    "property":"${this.data.property}",
    "address":"${this.data.address}",
    "shortName":"${this.data.shortName}",
    "provinceId":"${this.data.provinceId}",
    "cityId":"${this.data.cityId}",
    "districtId":"${this.data.districtId}",
    "id":"${this.data.id}"}`;
    const headerOptions = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8')
      .set('Authorization', 'Bearer ' + this.commonService.getToken());
    this.http.post('/api/地址', body, { headers: headerOptions })
      .subscribe((res: any) => {
        if (res.code === 1) {
          this.commonService.presentToast(res.message);
          this.dismiss();
        } else {
          this.commonService.presentToast(res.message);
        }
      });
  }

  /**
   * 保存
   */
  onSave() {
    this.disabledSave = true;
    // 验证
    if (this.dataValidation()) {
      if (this.data.id > 0) {
        this.edit();
      } else {
        this.add();
      }
    } else {
      this.disabledSave = false;
    }
    setTimeout(() => { this.disabledSave = false; }, 5000);
  }

  /**
   * 验证
   */
  dataValidation() {
    if (this.data.provinceId === '' || this.data.cityId === '' || this.data.districtId === '' || this.data.address.trim() === '') {
      this.commonService.presentAlertConfirm('行政区划和地址不能为空。');
      return false;
    }
    return true;
  }

  /**
   * 获取省份
   */
  async getProvinceList() {
    const headerOptions = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8')
      .set('Authorization', 'Bearer ' + await this.commonService.getToken());
    this.http.get('/api/地址', { headers: headerOptions })
      .subscribe((res: any) => {
        this.provinceData = res;
        if (this.data.provinceId !== '') {
          this.provinceText = this.provinceData.find(x => x.value === this.data.provinceId).label;
        }
      })

  }

  /**
   * 获取城市
   */
  async getCityList() {
    const headerOptions = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8')
      .set('Authorization', 'Bearer ' + await this.commonService.getToken());
    const condition = `?provinceId=${this.data.provinceId}`;
    this.http.get('/api/地址' + condition, { headers: headerOptions })
      .subscribe((res: any) => {
        this.cityData = res;
        if (this.data.cityId !== '') {
          this.cityText = this.cityData.find(x => x.value === this.data.cityId).label;
        }
      })
  }

  /**
   * 获取区县
   */
  async getDistrictList() {
    const headerOptions = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8')
      .set('Authorization', 'Bearer ' + await this.commonService.getToken());
    const condition = `?cityId=${this.data.cityId}`;
    this.http.get('/api/地址' + condition, { headers: headerOptions })
      .subscribe((res: any) => {
        this.districtData = res;
        if (this.data.districtId !== '') {
          this.districtText = this.districtData.find(x => x.value === this.data.districtId).label;
        }
      })
  }

  /**
   * 改变省份下拉菜单事件
   */
  provinceChange(value: string): void {
    this.getCityList();
    if (this.data.provinceId !== '' && this.provinceData.length > 0) {
      this.provinceText = this.provinceData.find(x => x.value === this.data.provinceId).label;
    }
  }

  /**
   * 改变城市下拉菜单事件
   */
  cityChange(value: string): void {
    this.getDistrictList();
    if (this.data.cityId !== '' && this.cityData.length > 0) {
      this.cityText = this.cityData.find(x => x.value === this.data.cityId).label;
    }
  }

  /**
   * 地区下拉菜单事件
   */
  districtChange(ionicSelect: any) {
    if (this.data.districtId !== '' && this.districtData.length > 0) {
      this.districtText = this.districtData.find(x => x.value === this.data.districtId).label;
    }
  }

  /**
   * 关闭模态
   */
  dismiss() {
    this.modalController.dismiss({
      dismissed: true
    });
  }

}